import time

from selenium.webdriver.common.by import By

from ..common.element_function import ElementFunction
from ..common.ui.PageElement import PageElement
from ..exception.TestException import TestException
from ..exception.errorcode import ErrorCode


class Tabs(PageElement):

    def __getTabsTitle__(self):
        # script = "var list = '';$(arguments[0]).children('ul.ui-tabs-nav').children('li[role=tab]').each(function(index, time){(list+=$(this).text().trim() +',')}); return list"
        script = "var list = '';$(arguments[0]).find('ul[role=tablist]').children('li[role=tab]').each(function(index, time){(list+=$(this).text().trim() +',')}); return list"
        tabsTitle = self._execute_script(script, self._get_web_element())
        tabsTitle = tabsTitle.split(',')
        tabsTitle.remove('')
        return tabsTitle

    # 有时候会失效，并且不报错
    # def setValue(self, value):
    #     self.wait_element_presence()
    #     tabsTitle = self.__getTabsTitle__()
    #     for index, title in enumerate(tabsTitle):
    #         if title == value:
    #             # script = "$(arguments[0]).tabs('option', 'active', {index})".format(index=index)
    #             # 不使用fish方法，找到对应连接处理，防止开发特殊处理tabs,如多个ul>li>a对应一个div
    #             script = "$(($(arguments[0]).find('ul[role=tablist]').children('li[role=tab]')[{index}])).children('a').click()".format(index=index)
    #             self._execute_script(script, self._get_web_element())
    #             return
    #     raise TestException.by_error_code(ErrorCode.TABS_VALUE_NOT_EXIST, value=value)

    def setValue(self, value):
        self.wait_element_presence()
        tab_elements = self._get_table_elements()
        for tab_element in tab_elements:
            title = tab_element.text.strip()
            if title == value:
                # 尝试3次, 很无奈
                try_count = 3
                while try_count > 0:
                    ElementFunction(self._driver).click(tab_element)
                    if self._is_active(tab_element):
                        break
                    try_count -= 1
                    time.sleep(1)
                if not self._is_active(tab_element):
                    raise TestException.by_error_code(ErrorCode.ELEMENT_OPERATE_FAILED,
                                                          message='tab {0} selected failed'.format(value))
                break
        else:
            raise TestException.by_error_code(ErrorCode.TABS_VALUE_NOT_EXIST, value=value)

    def click(self, selectTabTitle):
        self.wait_element_ready()
        self.setValue(selectTabTitle)

    def _get_table_elements(self):
        element = self._get_web_element();
        selector = 'ul[role=tablist] li[role=tab]'
        tab_elements = element.find_elements(By.CSS_SELECTOR, selector)
        return tab_elements

    def _is_active(self, element):
        return 'ui-tabs-active' in element.get_attribute('class')

    def get_identification(self):
        identification = {'data-ui-role': ['tabs', 'ui-tabs']}
        return identification
